package com.ray.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //重写快捷键 alt+insert alt+o
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 授权   首页所有人访问，功能页要有权限
        http.authorizeRequests()
                //首页所有人访问
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //跨站请求伪造，类似防火墙
        http .csrf().disable();
        //开启登录,无权限跳转
        http.formLogin()
                //自定义登录页
            .loginPage("/toLogin")
                //登录方法参数
            .usernameParameter("username")
            .passwordParameter("password")
                //使用自带登录方法
            .loginProcessingUrl("/login");

        //开启记住我//保存两周
        http.rememberMe().rememberMeParameter("rememberMe");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //数据库中读取
//        auth.jdbcAuthentication().dataSource()

        //内存中读取，
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("ray").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
